﻿using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Mvc;
using Ninject;
using Spotted.Web.Data;
using Spotted.Web.Data.DataProvider;
using Spotted.Web.Data.Entities;
using Spotted.Web.Data.Result;
using Spotted.Web.Data.ViewModel;
using Spotted.WebApi.Models;

namespace Spotted.WebApi.Controllers
{
    public class UserController : ApiController
    {
        [Inject]
        public IUserDataProvider UserDataProvider { get; set; }

        public IEnumerable<User> Get()
        {
            return null;
        }

        // create a user
        public CreateUserResult Post(CreateUserViewModel viewModel)
        {
            if (!ModelState.IsValid)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotAcceptable)
                    {
                        ReasonPhrase = ModelState.Values.First().Errors[0].ErrorMessage
                    });
            }

            // convert the viewmodel to the coorresponding model
            User user = new User
                {
                    EmailAddress = viewModel.EmailAddress,
                    FirstName = viewModel.FirstName,
                    LastName = viewModel.LastName,
                    Password = viewModel.Password
                };

            var result = UserDataProvider.CreateUser(user);
            if (result.ResultCode == ResultCode.DuplicateEmail)
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Conflict)
                    {ReasonPhrase = "Duplicate Email Address exists"});

            return result;
        }

        // update a user
        public UpdateUserResult Put(UpdateUserViewModel existingUser)
        {
            return null;
        }
    }
}
